const   fs = require('fs'),
    https = require('https'),
    http = require('http'),
    httpProxy = require('http-proxy'),
    path = require('path'),
    url = require("url"),
    sys = require("sys");

module.exports.run = function(country) {
    this.createServer(country);
};

module.exports.createServer = function(country) {
    var bsoi = http.createServer(function(req, res) {
        function notFound(req, res) {
            var NOT_FOUND = "Not Found\n";
            res.writeHead(404, [["Content-Type", "text/plain"], ["Content-Length", NOT_FOUND.length]]);
            res.write(NOT_FOUND);
            res.end();
        }
        if (req.method === "GET" || req.method === "HEAD" || req.method === "POST") {
            var handler = bsoi.getMapping[url.parse(req.url).pathname] || notFound;

            res.simpleText = function(code, body) {
                res.writeHead(code, [ [ "Content-Type", "text/plain" ],	[ "Content-Length", body.length ] ]);
                res.write(body);
                res.end();
            };

            res.simpleJSON = function(code, obj) {
                var body = JSON.stringify(obj);
                res.writeHead(code, [ [ "Content-Type", "text/json" ], [ "Content-Length", body.length ] ]);
                res.write(body);
                res.end();
            };

            handler(req, res);
        }
    });

    bsoi.countryCode = country;

    bsoi.getMapping = {};
    bsoi.get = function (path, handler) {
        bsoi.getMapping[path] = handler;
    };

    bsoi.readJSONfile = function(fileName, callback){
        fileName = fileName.replace('/country', '/' + country);
        fs.readFile(fileName, 'utf8', function(err, data) {
            if (err) throw err;
            callback(data);
        });
    };
    bsoi.staticHandler = function (filename) {
        filename = filename.replace('/country', '/' + country);
        function extname (path) {
            var index = path.lastIndexOf(".");
            return index < 0 ? "" : path.substring(index);
        };
        var body, headers;
        var content_type = bsoi.mime.lookupExtension(extname(filename));
        var encoding = (content_type.slice(0,4) === "text" ? "utf8" : "binary");

        function loadResponseData(callback) {
            if (body && headers) {
                callback();
                return;
            }

            sys.puts("loading " + filename + "...");
            fs.readFile(filename, encoding, function (err, data) {
                if (err) {
                    sys.puts("Error loading " + filename);
                } else {
                    body = data;
                    headers = [["Content-Type", content_type ], [ "Content-Length" , body.length]];

                    headers.push(["Cache-Control", "public"]);

                    sys.puts("static file " + filename + " loaded");
                    callback();
                }
            });
        };

        return function (req, res) {
            loadResponseData(function () {
                res.writeHead(200, headers);
                res.write(body, encoding);
                res.end();
            });
        };
    };
    bsoi.mime = {
        lookupExtension : function(ext, fallback) {
            return bsoi.mime.TYPES[ext.toLowerCase()] || fallback || 'application/octet-stream';
        },
        TYPES : {".html"  : "text/html",
            ".js"    : "application/javascript",
            ".json"  : "application/json",
            ".png"   : "image/png",
            ".xml"   : "application/xml"
        }
    };

    bsoi.get("/bsoi/services/security/initLogin", bsoi.staticHandler("server/mock/bsoi/services/security/country/login/initLogin-success.json"));

    bsoi.get("/bsoi/services/security/login", function(req, res){
        var body='';
        bsoi.get("/bsoi/services/security/logout", bsoi.staticHandler("server/mock/bsoi/services/security/country/logout/logout-success.json"));
        req.on('data', function (data) {
            body +=data;
        });
        req.on('end',function(){
            var resultObject = JSON.parse(body);
            var t_userId = resultObject.loginRequest.userId,
                t_password = resultObject.loginRequest.password;

//            if(t_userId === 'INUSER001' && t_password === 'password' ){
            bsoi.readJSONfile("server/mock/bsoi/services/security/country/login/login-success.json", function(data){
                res.simpleJSON(200, JSON.parse(data));
            });
//            }else{
//                bsoi.readJSONfile("server/mock/bsoi/services/security/country/login/login-error.json", function(data){
//                    res.simpleJSON(200, JSON.parse(data));
//                });
//            }
        });
    });

    bsoi.get("/bsoi/services/security/validate2FAToken", function(req, res){
        var body='';
        req.on('data', function (data) {
            body +=data;
        });
        req.on('end',function(){
            var resultObject = JSON.parse(body);
            var t_otpToken = resultObject.validate2FARequest.otpToken;

            bsoi.readJSONfile("server/mock/bsoi/services/security/country/validate-2FA-token/validate-2FA-token-success.json", function(data){
                res.simpleJSON(200, JSON.parse(data));
            });
            /*
            if(t_otpToken === '123456'){
                bsoi.readJSONfile("server/mock/bsoi/services/security/country/validate-2FA-token/validate-2FA-token-success.json", function(data){
                    res.simpleJSON(200, JSON.parse(data));
                });
            }else if(t_otpToken === '111111'){
                bsoi.readJSONfile("server/mock/bsoi/services/security/country/validate-2FA-token/validate-2FA-token-expired.json", function(data){
                    res.simpleJSON(200, JSON.parse(data));
                });
            }else{
                bsoi.readJSONfile("server/mock/bsoi/services/security/country/validate-2FA-token/validate-2FA-token-error.json", function(data){
                    res.simpleJSON(200, JSON.parse(data));
                });
            }
            */
        });
    });
    bsoi.get("/bsoi/services/security/resendOTP", bsoi.staticHandler("server/mock/bsoi/services/security/country/resend-OTP/resend-OTP.json"));
    bsoi.get("/bsoi/services/security/renewOTP", bsoi.staticHandler("server/mock/bsoi/services/security/country/renew-OTP/renew-OTP.json"));
    bsoi.get("/bsoi/services/mail/list", function(req, res){
        var body='';
        req.on('data', function (data) {
            body +=data;
        });
        req.on('end',function(){
            var resultObject = JSON.parse(body),
                t_mailType = resultObject.mailType;

            if(t_mailType === 'MAIL-TYPE-INBOX'){
                bsoi.readJSONfile("server/mock/bsoi/services/security/mailbox/mailbox.json", function(data){
                    res.simpleJSON(200, JSON.parse(data));
                });
            }else{
                bsoi.readJSONfile("server/mock/bsoi/services/security/mailbox/sent.json", function(data){
                    res.simpleJSON(200, JSON.parse(data));
                });
            }
        });
    });
    bsoi.get("/bsoi/services/mail/send", bsoi.staticHandler("server/mock/bsoi/services/security/mailbox/compose.json"));
    bsoi.get("/bsoi/services/mail/detail", bsoi.staticHandler("server/mock/bsoi/services/security/mailbox/detail.json"));
    bsoi.get("/bsoi/services/common/configurations", bsoi.staticHandler("server/mock/bsoi/services/security/mailbox/category.json"));

    bsoi.get("/bsoi/services/resource/list", bsoi.staticHandler("server/mock/bsoi/services/security/profiles/resourceList.json"));
    bsoi.get("/bsoi/services/personalization/account/addUpdate", bsoi.staticHandler("server/mock/bsoi/services/security/profiles/addUpdate.json"));

    bsoi.get("/bsoi/services/product/list", bsoi.staticHandler("server/mock/bsoi/services/security/country/product/productList.json"));
    bsoi.get("/bsoi/services/security/logout", bsoi.staticHandler("server/mock/bsoi/services/security/country/logout/logout-success.json"));

    bsoi.get("/bsoi/services/product/account/history", bsoi.staticHandler("server/mock/bsoi/services/security/country/account-history/account-history.json"));
    bsoi.get("/bsoi/services/product/card/history", bsoi.staticHandler("server/mock/bsoi/services/security/country/card-history/card-history.json"));
    bsoi.get("/bsoi/services/product/loan/history", bsoi.staticHandler("server/mock/bsoi/services/security/country/loan-history/loan-history.json"));

    bsoi.get("/bsoi/services/payment/history", bsoi.staticHandler("server/mock/bsoi/services/security/country/payment-history/payment-history.json"));
    bsoi.get("/bsoi/services/payment/history/details", bsoi.staticHandler("server/mock/bsoi/services/security/country/payment-detail/payment-detail.json"));
    bsoi.get("/bsoi/services/product/account/detail", bsoi.staticHandler("server/mock/bsoi/services/security/country/account-detail/account-detail.json"));
    bsoi.get("/bsoi/services/product/card/detail", bsoi.staticHandler("server/mock/bsoi/services/security/country/card-detail/card-detail.json"));
    bsoi.get("/bsoi/services/product/loan/detail", bsoi.staticHandler("server/mock/bsoi/services/security/country/loan-detail/loan-detail.json"));

    bsoi.get("/bsoi/services/product/list/filter", function(req, res){
        var body='';
        req.on('data', function (data) {
            body +=data;
        });
        req.on('end',function(){
            var resultObject = JSON.parse(body),
                t_functionCode = resultObject.productFilter.functionCode,
                t_crDrFlag = resultObject.productFilter.crDrFlag;

            if((t_functionCode === 'FUNC_FT_CARD_PAYMENT' && t_crDrFlag === 'CR') || (t_functionCode === 'PAYMENT_CARD' && t_crDrFlag === 'CR')){
                bsoi.readJSONfile("server/mock/bsoi/services/security/country/scb-cardList/scb-cardList.json", function(data){
                    res.simpleJSON(200, JSON.parse(data));
                });
            }else{
                bsoi.readJSONfile("server/mock/bsoi/services/security/country/filter-product/filter-product-list.json", function(data){
                    res.simpleJSON(200, JSON.parse(data));
                });
            }
        });
    });

    bsoi.get("/bsoi/services/payee/thirdparty/list", bsoi.staticHandler("server/mock/bsoi/services/security/country/thirdparty-payee-list/thirdparty-payee-list.json"));
    bsoi.get("/bsoi/services/payee/biller/list", bsoi.staticHandler("server/mock/bsoi/services/security/country/viewandpaybils-payee-list/viewandpaybils-payee-list.json"));
    bsoi.get("/bsoi/services/payment/transfer/thirdparty", bsoi.staticHandler("server/mock/bsoi/services/security/country/thirdparty-payee-list/thirdparty-transfer-result.json"));
    bsoi.get("/bsoi/services/payment/transfer/own", bsoi.staticHandler("server/mock/bsoi/services/security/country/own-transfer/own-transfer-result.json"));
    bsoi.get("/bsoi/services/payment/cardpayment", bsoi.staticHandler("server/mock/bsoi/services/security/country/scb-cardPayment-result/scb-cardPayment-result.json"));
    bsoi.get("/bsoi/services/payee/billpayment/list", bsoi.staticHandler("server/mock/bsoi/services/security/country/billpayment-payee-list/billpayment-payee-list.json"));
    bsoi.get("/bsoi/services/payment/bill/presentment", bsoi.staticHandler("server/mock/bsoi/services/security/country/bill-presentment/bill-presentment.json"));
    //bsoi.get("/bsoi/services/payment/bill", bsoi.staticHandler("server/mock/bsoi/services/security/country/payment-bill/payment-bill-result.json"));
    bsoi.get("/bsoi/services/payee/anyCard/list", bsoi.staticHandler("server/mock/bsoi/services/security/country/any-cardList/any-cardList.json"));
    bsoi.get("/bsoi/services/payment/transfer/anyCard", bsoi.staticHandler("server/mock/bsoi/services/security/country/any-cardPayment-result/any-cardPayment-result.json"));
    
    bsoi.get("/bsoi/services/common/get/txn/fxrate", bsoi.staticHandler("server/mock/bsoi/services/security/country/fx-rate/fx-rate.json"));

//    bsoi.get("/bsoi/services/help/list", bsoi.staticHandler("server/mock/bsoi/services/security/help/help.json"));
//    bsoi.get("/bsoi/services/about", bsoi.staticHandler("server/mock/bsoi/services/security/country/about/aboutus.json"));
//    bsoi.get("/bsoi/services/maintenance/list", bsoi.staticHandler("server/mock/bsoi/services/security/maintenance/maintenance.json"));
//    bsoi.get("/bsoi/services/notification/list", bsoi.staticHandler("server/mock/bsoi/services/security/notification/notification.json"));

    bsoi.get("/bsoi/services/payment/authorize/view", bsoi.staticHandler("server/mock/bsoi/services/security/country/authorise/authorise-list.json"));
    bsoi.get("/bsoi/services/payment/etac/regenerate", bsoi.staticHandler("server/mock/bsoi/services/security/country/authorise/regenerate-etac.json"));

    bsoi.get("/bsoi/services/payment/bill", function(req, res){
        if('in' === bsoi.countryCode){
            var body='';
            req.on('data', function (data) {
                body +=data;
            });
            req.on('end',function(){
                var resultObject = JSON.parse(body);
                if(resultObject.payment.txnPassword !== null 
                    && resultObject.requestHeader.serviceContext.otpToken === null){
                    bsoi.readJSONfile("server/mock/bsoi/services/security/country/payment-bill/getOTP.json", function(data){
                        res.simpleJSON(200, JSON.parse(data));
                    });
                }else{
                    bsoi.readJSONfile("server/mock/bsoi/services/security/country/payment-bill/payment-bill-result.json", function(data){
                        res.simpleJSON(200, JSON.parse(data));
                    });
                }
            });
        }else if('sg' === bsoi.countryCode){
        	var body='';
            req.on('data', function (data) {
                body +=data;
            });
            req.on('end',function(){
            	var resultObject = JSON.parse(body);
            	if(resultObject.requestHeader.serviceContext.otpToken === null){
            		bsoi.readJSONfile("server/mock/bsoi/services/security/country/payment-bill/payment-bill-result.json", function(data){
            			res.simpleJSON(200, JSON.parse(data));
            		});
            	}else if(resultObject.requestHeader.serviceContext.otpToken === '111111'){
            		bsoi.readJSONfile("server/mock/bsoi/services/security/country/payment-bill/payment-bill-mastoken-success.json", function(data){
            			res.simpleJSON(200, JSON.parse(data));
            		});
            	}else if(resultObject.requestHeader.serviceContext.otpToken === '222222'){
            		bsoi.readJSONfile("server/mock/bsoi/services/security/country/payment-bill/payment-bill-mastoken-exceeded.json", function(data){
            			res.simpleJSON(200, JSON.parse(data));
            		});
            	}else{
            		bsoi.readJSONfile("server/mock/bsoi/services/security/country/payment-bill/payment-bill-mastoken-error.json", function(data){
            			res.simpleJSON(200, JSON.parse(data));
            		});
            	}
            });
        }else{
            bsoi.readJSONfile("server/mock/bsoi/services/security/country/payment-bill/payment-bill-result.json", function(data){
                res.simpleJSON(200, JSON.parse(data));
            });
        }
    });

    bsoi.get("/bsoi/services/payee/merchant/list", bsoi.staticHandler("server/mock/bsoi/services/security/country/add-payee/merchant-list.json"));
    bsoi.get("/bsoi/services/payee/billpayment/add", function(req, res){
        var body='';
        req.on('data', function (data) {
            body +=data;
        });
        req.on('end',function(){
            var resultObject = JSON.parse(body),
                t_otpToken = resultObject.requestHeader.serviceContext.otpToken;

            if(t_otpToken === '123456'){
                bsoi.readJSONfile("server/mock/bsoi/services/security/country/add-payee/add-payee-invalid.json", function(data){
                    res.simpleJSON(200, JSON.parse(data));
                });
            }else{
                bsoi.readJSONfile("server/mock/bsoi/services/security/country/add-payee/add-payee-success.json", function(data){
                    res.simpleJSON(200, JSON.parse(data));
                });
            }
        });
    });

    bsoi.get("/bridgeheadi18n/channels/channelDetails", bsoi.staticHandler("server/mock/bsoi/services/id/locate/channelDetails.json"));
    bsoi.get("/bridgeheadi18n/channels/placemarks",bsoi.staticHandler("server/mock/bsoi/services/id/locate/placemarks.json"));
    bsoi.get("/bridgeheadi18n/channels/regionarea",bsoi.staticHandler("server/mock/bsoi/services/id/locate/region.json"));

    bsoi.listen(5555, null);
};
